#ifndef CUBES_FIND_TARGET_H
#define CUBES_FIND_TARGET_H

int game_restart()
{
    SDL_Delay(1000);
    create_cubes();
    wait(Wait_Clear);
    return 1;
}

float get_rotation_speed(int level)
{
    float ds, step;
    ds = Max_Rotation_Speed - Rotation_Speed;
    step = ds/(Levels_Count-1);
    return Rotation_Speed + step*(level-1);
}

int cube_select_target(Cube_P cube)
{
    int i;
    Cube_P target;
    float x;
    float y;
    float cosB;
    float B;
    float* angles;
    float res_angle;
    int res_ID;
    float angle;
    angles = malloc(CC*sizeof(float));
    for(i = 0; i < CC; ++i) 
    {
        target = &cubes[i];
        angles[i] = 777;
        if(!target->enabled)
            continue;
        if(target->ID == cube->ID)
            continue;
        if(target->state == State_Moving)
            continue;
        x = target->x - cube->x;
        y = target->y - cube->y;
        cosB = y / sqrtf(x*x + y*y);
        B = acos(cosB);
        B = rads_to_degs(B);
        
        if(x < 0) {
            B = -B;
        }
        
        if(fabs(B)>180) {
            printf("Angle %f", B);
        }
        
        angles[i] = normalize_angle(B - cube->angle);
    }
    res_angle = 777;
    res_ID = CC;
    for(i = 0; i < CC; ++i) 
    {
        angle = angles[i];
        if(fabs(angle) < fabs(res_angle)) {
            res_angle = angle;
            res_ID = i;
        }
    }
    free(angles); angles = 0;
    if(res_ID == CC) {
        //game_restart();
        return 2;
    }
    cube->target = &cubes[res_ID];
    cube->delta_angle = get_rotation_speed(cube->level);
    if(res_angle < 0) {
        cube->delta_angle = - cube->delta_angle;
    }
    cube->max_rotation = fabs(res_angle);
    cube->rotated = 0;
    cube->end_angle = normalize_angle(
        cube->angle+res_angle );
    cube->state = State_Rotating;
    //printf("Selected target, angle %f, ID %d -> %d\n", 
        //res_angle, cube->ID, res_ID);
    return 1;
}

int cubes_select_target()
{
    int i;
    for(i = 0; i < CC; ++i) 
    {
        if(!cubes[i].enabled)
            continue;
        if(cubes[i].target != 0)
            continue;
        if(cubes[i].state != State_Search)
            continue;
        if(cube_select_target(&cubes[i]) == 2)
            return 2;
    }
    return 1;
}

#endif 
